package com.android.manghe.detail.precenter;

import android.text.TextUtils;
import com.android.base.frame.presenter.XPresenter;
import com.android.base.okhttp.okUtil.OKHttpUtil;
import com.android.base.okhttp.okUtil.base.NetBean;
import com.android.base.tools.BigDecimalUtils;
import com.android.base.tools.EmptyUtil;
import com.android.base.tools.ToastUtil;
import com.android.manghe.cache.ConfigHolder;
import com.android.manghe.cache.UserHolder;
import com.android.manghe.common.model.*;
import com.android.manghe.config.ConstantsUrl;
import com.android.manghe.detail.activity.GoodDetailActivity;
import com.android.manghe.detail.model.*;
import com.android.manghe.mine.model.UserRes;
import com.google.gson.Gson;
import okhttp3.Call;

import java.util.*;

public class PGoodDetail extends XPresenter<GoodDetailActivity> {
    public String orderId = "";
    public String auctionId = "";
    public String order_sn = "";
    public boolean isCollect;
    public boolean isInitJoinLog;
    public boolean isYouMost;
    public AuctionDetailRes.AuctionBean auctionBean;
    public AuctionOrderDetailRes.DataBean orderBean;
    public List<PeopleGotRes.ListBean> currentGotPeopleList;

    public boolean isEnd;//竞价是否结束了

    public String userId = "";

    public void init() {
        userId = UserHolder.getUID(getV());
    }

    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }

    public void setAuctionId(String auctionId) {
        this.auctionId = auctionId;
    }

    public void loadData() {
        HashMap<String, String> headMap = new HashMap<>();
        headMap.put("UID", UserHolder.getUID(getV()));
        headMap.put("TOKEN", UserHolder.getUserInfo(getV()).TOKEN);
headMap.put("PLATFORM", "android");
        HashMap<String, String> dataMap = new HashMap<>();
        dataMap.put("order_id", orderId);
        new OKHttpUtil(getV()).urlByHeadData(ConstantsUrl.domain + ConstantsUrl.ACUTIONORDER_DETAIL, dataMap, headMap)
                .get()
                .execute(new BaseBack<AuctionOrderDetailRes>() {

                    @Override
                    public void onSuccess(Call call, AuctionOrderDetailRes res) {
                        if (res != null && res.code == 0 && res.data != null) {
                            orderBean = res.data;
                            auctionId = res.data.auction_id;
                            order_sn = res.data.order_sn;
                            getV().updateView(res.data);
                            loadGotPeople(order_sn);
                            loadShareList(true);
                            loadPreviousDealList(true);
                            getCollectStatus();
                        } else {
                            ToastUtil.showShort(getV(), "数据出错，请稍后重试");
                        }
                    }

                    @Override
                    public void onFailure(Exception e) {
                        super.onFailure(e);
                        ToastUtil.showShort(getV(), "加载数据失败，请检查您的网络");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public void getCollectStatus() {
        HashMap<String, String> headMap = new HashMap<>();
        headMap.put("UID", UserHolder.getUID(getV()));
        headMap.put("TOKEN", UserHolder.getUserInfo(getV()).TOKEN);
headMap.put("PLATFORM", "android");
        HashMap<String, String> dataMap = new HashMap<>();
        dataMap.put("auction_id", auctionId);
        new OKHttpUtil(getV()).urlByHeadData(ConstantsUrl.domain + ConstantsUrl.GetCollect, headMap)
                .post(dataMap)
                .build()
                .execute(new BaseBack<CheckFavoriteRes>() {
                    @Override
                    public void onSuccess(Call call, CheckFavoriteRes netBean) {
                        if (netBean != null && netBean.code == 0) {
                            isCollect = netBean.data.is_favorite == 1;
                            getV().setCollectStatus(isCollect);
                        }
                    }

                    @Override
                    public void onFailure(Exception e) {
                        super.onFailure(e);
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    public void loadConfig() {
        new OKHttpUtil(getV()).url(ConstantsUrl.domain + ConstantsUrl.ACUTIONCONFIG)
                .get()
                .execute(new BaseBack<AuctionConfig>() {
                    @Override
                    public void onSuccess(Call call, AuctionConfig res) {
                        if (res.code == 0 && res.data != null) {
                            ConfigHolder.setConfigInfo(getV(), res.data);
                            getV().setLangView();
                        }
                    }

                    @Override
                    public void onFailure(Exception e) {
                        super.onFailure(e);
                    }
                });
    }

    public void changeCollectStatus() {
        getV().showLoadingDialog();
        HashMap<String, String> headMap = new HashMap<>();
        headMap.put("UID", UserHolder.getUID(getV()));
        headMap.put("TOKEN", UserHolder.getUserInfo(getV()).TOKEN);
headMap.put("PLATFORM", "android");
        HashMap<String, String> dataMap = new HashMap<>();
        dataMap.put("auction_id", auctionId);
        new OKHttpUtil(getV()).urlByHeadData(ConstantsUrl.domain + (isCollect ? ConstantsUrl.CancelCollection : ConstantsUrl.AddCollect), headMap)
                .post(dataMap)
                .build()
                .execute(new BaseBack<NetBean>() {
                    @Override
                    public void onSuccess(Call call, NetBean netBean) {
                        getV().hideLoadingDialog();
                        if (netBean != null && netBean.code == 0) {
                            isCollect = !isCollect;
                            getV().setCollectStatus(isCollect);
                        } else {
                            ToastUtil.showShort(getV(), "操作失败");
                        }
                    }

                    @Override
                    public void onFailure(Exception e) {
                        super.onFailure(e);
                        getV().hideLoadingDialog();
                        ToastUtil.showShort(getV(), "收藏失败");
                    }

                    @Override
                    public void onComplete() {
                        getV().hideLoadingDialog();
                    }
                });
    }


    private Timer timer;

    public void loadDetailBySocket() {
        isRefreshedBottomHttpListViews = false;
        initAuction();

        if (timer == null) {
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    getAuction();
                }
            }, 0, 1000);
        }
    }

    public void getAuction() {
        String uid = UserHolder.getUID(getV().getApplicationContext());
        AuctionSocketReq auction = new AuctionSocketReq();
        auction.id = auctionId;
        auction.type = "get_auction";
        if (EmptyUtil.check(uid)) {
            auction.mid = -1;
        } else {
            auction.mid = Integer.parseInt(uid);
        }
        String sendJson = new Gson().toJson(auction);
        getV().sendText(sendJson);
    }

    public void getAutoJoinAuction() {
        AutoJoinAuctionSocketReq reqData = new AutoJoinAuctionSocketReq();
        reqData.id = Integer.parseInt(auctionId);
        reqData.mid = Integer.parseInt(UserHolder.getUID(getV()));
        reqData.token = UserHolder.getUserInfo(getV()).TOKEN;
        reqData.type = "get_auto_join_auction";
        getV().sendText(new Gson().toJson(reqData));
    }

    public void initJoinLog() {
        JoinLogSocketReq reqData = new JoinLogSocketReq();
        reqData.order_sn = order_sn;
        reqData.page = 1;
        reqData.per_page = 3;
        reqData.type = "join_log";
        getV().sendText(new Gson().toJson(reqData));
    }


    public void toOffer(int count, final boolean isAddmore) {
        getV().showLoadingDialog();
        HashMap<String, String> headMap = new HashMap<>();
        headMap.put("UID", UserHolder.getUID(getV()));
        headMap.put("TOKEN", UserHolder.getUserInfo(getV()).TOKEN);
headMap.put("PLATFORM", "android");
        HashMap<String, String> dataMap = new HashMap<>();
        dataMap.put("mid", UserHolder.getUID(getV()));
        dataMap.put("auction_id", auctionId);
        dataMap.put("token", UserHolder.getUserInfo(getV()).TOKEN);
        dataMap.put("count", count + "");
        new OKHttpUtil(getV()).urlByHeadData(ConstantsUrl.domain + ConstantsUrl.AUTO_OFFER, headMap)
                .post(dataMap)
                .build()
                .execute(new BaseBack<NetBean>() {
                    @Override
                    public void onSuccess(Call call, NetBean netBean) {
                        getV().hideLoadingDialog();
                        if (netBean != null) {
                            if (netBean.code == 0) {
                                ToastUtil.showShort(getV(), isAddmore ? "追加成功" : "开始自动出价");
                                getAutoJoinAuction();
                            } else {
                                ToastUtil.showShort(getV(), netBean.msg);
                            }
                        } else {
                            ToastUtil.showShort(getV(), "出价失败");
                        }
                    }

                    @Override
                    public void onFailure(Exception e) {
                        super.onFailure(e);
                        getV().hideLoadingDialog();
                        ToastUtil.showShort(getV(), "出价失败");
                    }

                    @Override
                    public void onComplete() {
                        getV().hideLoadingDialog();
                    }
                });
    }

    public void initAuction() {
        String uid = UserHolder.getUID(getV().getApplicationContext());
        AuctionSocketReq auction = new AuctionSocketReq();
        auction.id = auctionId;
        auction.type = "into_auction";
        if (EmptyUtil.check(uid)) {
            auction.mid = -1;
        } else {
            auction.mid = Integer.parseInt(uid);
        }
        String sendJson = new Gson().toJson(auction);
        getV().sendText(sendJson);
    }


    public void toOfferOneTime() {
        AuctionSocketReq auction = new AuctionSocketReq();
        auction.type = "join_auction";
        auction.id = auctionId;
        auction.mid = Integer.parseInt(UserHolder.getUID(getV().getApplicationContext()));
        auction.token = UserHolder.getUserInfo(getV().getApplicationContext()).TOKEN;
        String sendJson = new Gson().toJson(auction);
        getV().sendText(sendJson);
    }
    private UserRes.UserInfo userInfo;

    public UserRes.UserInfo getUserInfo() {
        if (userInfo == null) {
            userInfo = UserHolder.getUserInfo(getV());
        }
        return userInfo;
    }

    public void quitAuction() {
        String uid = UserHolder.getUID(getV().getApplicationContext());
        AuctionSocketReq auction = new AuctionSocketReq();
        auction.id = auctionId;
        auction.type = "quit_auction";
        if (EmptyUtil.check(uid)) {
            auction.mid = -1;
        } else {
            auction.mid = Integer.parseInt(uid);
        }
        String sendJson = new Gson().toJson(auction);
        getV().sendText(sendJson);
    }

    private boolean isRefreshedBottomHttpListViews = false;

    public void dealSocketData(String json) {
        try {
            if (!EmptyUtil.check(json)) {
                if (json.contains("get_auction")) {
                    try {
                        AuctionDetailRes socketRes = new Gson().fromJson(json, AuctionDetailRes.class);
                        if (!EmptyUtil.check(socketRes) && !EmptyUtil.check(socketRes.auction) && socketRes.auction.id.equals(auctionId)) {
                            auctionBean = socketRes.auction;
                            order_sn = socketRes.auction.order_sn;
                            if (!isRefreshedBottomHttpListViews) {
                                isRefreshedBottomHttpListViews = true;
                                loadShareList(true);
                                loadPreviousDealList(true);
                            }
                            if (!isInitJoinLog) {
                                isInitJoinLog = true;
                                initJoinLog();
                            }

                            getV().updateViewBySocket(auctionBean);
                        }
                    } catch (Exception e) {

                    }
                } else if (!isEnd && json.contains("into_auction")) {
                    try {
                        InitAuctionRes initAuctionRes = new Gson().fromJson(json, InitAuctionRes.class);
                        if (!EmptyUtil.check(initAuctionRes) && TextUtils.equals(auctionId, initAuctionRes.auction_id)) {
                            getV().updateCollectionView(initAuctionRes);
                        }
                    } catch (Exception e) {

                    }
                } else if (!isEnd && json.contains("get_auto_join_auction")) {
                    try {
                        AutoJoinAuctionSocketRes socketRes = new Gson().fromJson(json, AutoJoinAuctionSocketRes.class);
                        if (!EmptyUtil.check(socketRes) && TextUtils.equals(auctionId, socketRes.id + "")) {
                            getV().updateAutoOfferView(socketRes);
                        }
                    } catch (Exception e) {

                    }
                } else if (!isEnd && json.contains("join_log")) {
                    try {
                        PeopleGotRes socketRes = new Gson().fromJson(json, PeopleGotRes.class);
                        getV().updateChuJia(socketRes.list);
                        currentGotPeopleList = socketRes.list;
                        getV().setNotice("<font color='#e84e40'>若无人出价,</font><font color='#b0120a'>" + socketRes.list.get(0).username
                                + "</font><font color='#e84e40'>将以</font>"
                                + "<font color='#b0120a'>¥" + socketRes.list.get(0).price + "</font><font color='#e84e40'>获得此物品</font>");
                    } catch (Exception e) {

                    }
                } else if (!isEnd && json.contains("join_auction")) {
                    try {
                        JoinAuctionRes socketRes = new Gson().fromJson(json, JoinAuctionRes.class);
                        if (socketRes.id == 0 && !TextUtils.isEmpty(socketRes.code) && !TextUtils.isEmpty(socketRes.msg)) {
                            ToastUtil.showLong(getV(), socketRes.msg);
                            return;
                        }
                        if (!TextUtils.isEmpty(auctionId) && (socketRes.id + "").equals(auctionId)) {
                            if(TextUtils.equals(socketRes.mid+"", getUserInfo().UID)){
                                ToastUtil.showShort(getV(), "出价成功");
                            }
                            initJoinLog();
                            initAuction();
                            isYouMost = (socketRes.id + "").equals(userId);
                        }
                    } catch (Exception e) {

                    }
                } else if (json.contains("auction_result")) {
                    try {
                        AuctionResultRes socketRes = new Gson().fromJson(json, AuctionResultRes.class);
                        if (!TextUtils.isEmpty(auctionId) && (socketRes.id + "").equals(auctionId)) {
                            isEnd = true;
                            String uid = UserHolder.getUID(getV());
                            if (!TextUtils.isEmpty(uid) && Integer.parseInt(uid) == socketRes.mid) {
                                //你中奖了，弹出框
                                getV().showWinDialog(socketRes.last_price + "");
                                return;
                            }
                            //更新为结束界面
                            if (socketRes.time > 0) {
                                if (auctionBean == null) {
                                    //可以进入最新一期
//                                    getV().toNexRound();
                                } else {
                                    boolean isHaveNext = "0".equals(BigDecimalUtils.mul(auctionBean.mid_count + "", auctionBean.brokerage + "", 0));
                                    if(!isHaveNext){
                                        getV().toNexRound();
                                    }else {
                                        //结束
                                        getV().gameOver();
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {

                    }
                }
            }
        } catch (
                Exception e) {
            e.printStackTrace();
        }

    }

    public void stopSocketTimer() {
        if (timer != null) {
            timer.cancel();
        }
    }

    public void loadGotPeople(String orderSN) {
        HashMap<String, String> dataMap = new HashMap<>();
        dataMap.put("page", "1");
        dataMap.put("size", "3");
        dataMap.put("order_sn", orderSN);
        new OKHttpUtil(getV()).urlByHeadData(ConstantsUrl.domain + ConstantsUrl.ACUTIONREJOINLOG, dataMap, null)
                .get()
                .execute(new BaseBack<PeopleGotRes>() {

                    @Override
                    public void onSuccess(Call call, PeopleGotRes res) {
                        if (res != null && res.code == 0 && res.list != null) {
                            getV().updateChuJia(res.list);
                        }
                    }

                    @Override
                    public void onFailure(Exception e) {
                        super.onFailure(e);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    private int shareListCurrentPage = 1;
    private List<ShareOrderRes.ListBean> shareList = new ArrayList<>();

    public void loadShareList(boolean isRefresh) {
        if (TextUtils.isEmpty(auctionId)) {
            loadData();
            return;
        }
        if (isRefresh) {
            shareListCurrentPage = 1;
            shareList.clear();
        }

        HashMap<String, String> dataMap = new HashMap<>();
        dataMap.put("page", shareListCurrentPage + "");
        dataMap.put("size", "10");
        dataMap.put("auction_id", auctionId);
        new OKHttpUtil(getV()).urlByHeadData(ConstantsUrl.domain + ConstantsUrl.ACUTIONCOMMENT, dataMap, null)
                .get()
                .execute(new BaseBack<ShareOrderRes>() {

                    @Override
                    public void onSuccess(Call call, ShareOrderRes res) {
                        if (res != null && res.code == 0 && res.data != null && res.data.list != null) {
                            shareList.addAll(res.data.list);
                            getV().updateShareOrder(shareList);
                            shareListCurrentPage++;
                        }
                    }

                    @Override
                    public void onFailure(Exception e) {
                        super.onFailure(e);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    private int previousDealCurrentPage = 1;
    private List<PreviousDealRes.ListBean> previousDealList = new ArrayList<>();

    public void loadPreviousDealList(boolean isRefresh) {
        if (TextUtils.isEmpty(auctionId)) {
            loadData();
            return;
        }
        if (isRefresh) {
            previousDealCurrentPage = 1;
            previousDealList.clear();
        }

        HashMap<String, String> dataMap = new HashMap<>();
        dataMap.put("page", previousDealCurrentPage + "");
        dataMap.put("size", "10");
        dataMap.put("auction_id", auctionId);
        new OKHttpUtil(getV()).urlByHeadData(ConstantsUrl.domain + ConstantsUrl.ACUTIONRECENTLYORDER, dataMap, null)
                .get()
                .execute(new BaseBack<PreviousDealRes>() {

                    @Override
                    public void onSuccess(Call call, PreviousDealRes res) {
                        if (res != null && res.code == 0 && res.data != null && res.data.list != null) {
                            previousDealList.addAll(res.data.list);
                            getV().updatePreviousDeal(previousDealList);
                            previousDealCurrentPage++;
                        }
                    }

                    @Override
                    public void onFailure(Exception e) {
                        super.onFailure(e);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
